package com.hspedu.event;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/2/13
 * @time 23:35
 * 演示小球通过键盘控制上下左右移动
 */
public class BallMove extends JFrame{
    private MyPanel myPanel;
    public BallMove(){
        if (myPanel == null){
            myPanel = new MyPanel();
        }
        this.add(myPanel);
        this.setSize(500,500);
        this.setVisible(true);
        this.addKeyListener(myPanel);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new BallMove();
    }
}

class MyPanel extends JPanel implements KeyListener {
    //初始化小球坐标
    int x = 100;
    int y = 100;

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        g.setColor(Color.black);
        g.fillOval(x,y,10,10);
    }


    /**
     * 有字符输出时，该方法就会触发
     * @param e
     */
    @Override
    public void keyTyped(KeyEvent e) {

    }

    /**
     * 当某个键按下，该方法会触发
     * @param e
     */
    @Override
    public void keyPressed(KeyEvent e) {
       // System.out.println((char) e.getKeyCode()+"被按下");
        //根据用户按下的键不同，来处理小球的移动
        //Java中给每一个键都分配了一个数值
        if (e.getKeyCode() == KeyEvent.VK_DOWN){
            //坐标上移
            y++;
        }else if (e.getKeyCode() == KeyEvent.VK_UP){
            //坐标下移
            y--;
        }else if (e.getKeyCode() == KeyEvent.VK_LEFT){
            //左移
            x--;
        }else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            //右移
            x++;
        }

        //重新绘图
        this.repaint();
    }

    /**
     * 当某个键被松开，该方法会触发
     * @param e
     */
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
